package org.mili.ticketeer.dao;

import org.mili.application.dao.AbstractDao;
import org.mili.application.dao.DaoException;
import org.mili.application.dao.DaoFactory;
import org.mili.application.dao.ModificationResult;
import org.mili.application.dao.RowTransformer;
import org.mili.application.dto.Identifieable;
import org.mili.ticketeer.dto.Ticket;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class TicketDao extends AbstractDao {

    private ContactDao contactDao = DaoFactory.getDao(ContactDao.class);

    public TicketDao() {
        super(Ticket.UniqueFields.values(), Ticket.Fields.values(), Ticket.TABLE);
    }

    public List<Ticket> getTickets() throws DaoException {
        return read(new RowTransformer<Ticket>() {
            @Override
            public Ticket transform(ResultSet resultSet) throws SQLException {
                Ticket ticket = new Ticket();
                ticket.setId(resultSet.getInt(Identifieable.Fields.ID.name()));
                ticket.setPriority(resultSet.getInt(Ticket.Fields.PRIORITY.name()));
                ticket.setGroup(resultSet.getInt(Ticket.Fields.GROUP.name()));
                ticket.setState(resultSet.getInt(Ticket.Fields.STATE.name()));
                ticket.setComment(resultSet.getString(Ticket.Fields.COMMENT.name()));
                ticket.setTitle(resultSet.getString(Ticket.Fields.TITLE.name()));
                ticket.setCompletedAt(resultSet.getTimestamp(Ticket.Fields.COMPLETEDAT.name()));
                ticket.setCreatedAt(resultSet.getTimestamp(Ticket.Fields.CREATEDAT.name()));
                return ticket;
            }
        });
    }

    public ModificationResult write(final Ticket ticket) throws DaoException {
        return createOrUpdate(ticket);
    }

}
